package com.zl.this0;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.config.TaskManagementConfigUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Async单独使用不能AopContext.currentProxy()，如果时混合即可可以
 *
 * 参考@Async + @Transaction混合
 * https://cloud.tencent.com/developer/article/1497700
 * Spring几种this错误
 * https://my.oschina.net/guangshan/blog/1807721
 *
 * this调用解决方案
 *   1.使用AspectJ强制代理
 *   2.applicationContext获取实例
 *   3.@EnableAspectJAutoProxy(proxyTargetClass = true,exposeProxy = true)
 *     注册@Async
 * @date 2021/6/28 15:31
 * @author Lizhong
 */
@Service
public class Mixed {

    @Transactional
    public void tx(){
        System.out.println("事务: "+Thread.currentThread().getName());
        Mixed o = (Mixed) AopContext.currentProxy();
        o.async();

    }
    @Async
    public void async (){
        //TODO 2021/6/28 15:33
        System.out.println("异步： "+Thread.currentThread().getName());
    }
    // 注册
    public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME);
            beanDefinition.getPropertyValues().add("exposeProxy", true);
        }
    }
}
